package cn.itcast.controller;

import cn.itcast.Client.UserClient;
import cn.itcast.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.xml.ws.Action;
import java.util.List;

@RestController
@RequestMapping("consumer")
@DefaultProperties(defaultFallback = "queryByIdFallBack")
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private UserClient userClient;

    @GetMapping("{id}")
    public User queryById(@PathVariable("id") Long id){
        return userClient.queryById(id);
    }

    /*   @GetMapping("{id}")
       public User queryById(@PathVariable("id")Long id){
           List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
           ServiceInstance instance = instances.get(0);
           String url = "http://"+instance.getHost()+":"+instance.getPort()+"/user/"+id;
   //        String url = "http://localhost:8081/user/"+id;
           User user= restTemplate.getForObject(url,User.class);
           return user;
       }*/
 /*   @GetMapping("{id}")
    @HystrixCommand
    public String queryById(@PathVariable("id") Long id) {
        String url = "http://user-service/user/" + id;
        String user = restTemplate.getForObject(url, String.class);
        return user;
    }
*/
 /*   @GetMapping("{id}")
    @HystrixCommand
    public String queryById(@PathVariable("id") Long id){
        if(id == 1){
            throw new RuntimeException("太忙了");
        }
        String url = "http://user-service/user/" + id;
        String user = restTemplate.getForObject(url, String.class);
        return user;
    }*/



    public String queryByIdFallBack() {
        return "亲爱的的用户,对不起，网络太拥挤了！";
    }

}
